/*
 * 全局请求封装
 * @param path 请求路径
 * @param method 请求类型(GET/POST等)
 * @oaram data 请求体数据
 * @param loading 请求未完成是是否显示加载中，默认为true
 */
import useStore from '@/stores';
import config from "./config.js";
export default (path, method, data = {}, loading = true) => {
	if (loading) {
		uni.showLoading({
			title: "加载中",
			mask: true
		});
	};
	return request(path, method, data, loading)
};

function request(path, method, data, loading) {
	const {
		globalStore
	} = useStore()
	return new Promise((resolve, reject) => {
		uni.request({
			url: config.BASE_URL + path,
			method: method,
			data,
			header: {
				"Authorization": globalStore.token ? 'Bearer ' + globalStore.token : "",
				'Cache-Control': 'no-cache'
			},
			success(res) {
				if (res.data.code === 401) {
					uni.$showModal({
						title: "",
						content: '登录状态已过期，请重新登录！',
						confirmVal: '确定',
						delCancel: true,
						cancelVal: '',
					}).then(() => {
						globalStore.clearLoginInfo()
					})
				} else if (config.RESOLVE_CODES.some(c => c == res.data.code)) {
					resolve(res.data);
				} else {
					if (res.data.code === 50002) {
						uni.$showModal({
							title: "",
							content: '钱包余额不足, 是否去充值？',
							confirmVal: '确定',
							cancelVal: '取消'
						}).then(() => {
							uni.navigateTo({
								url: "/pages_mine/pay/index"
							})
						})
					} else {
						uni.$uv.toast(res.data.msg || res.data.message);
						reject(res.data);
					}
				}
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}